package com.example.mywanandroid.util;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.os.Build;
import android.os.Parcelable;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import androidx.collection.ArrayMap;
import androidx.fragment.app.Fragment;

import com.google.zxing.WriterException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {

    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    /**
     * 判断是否为图片格式
     *
     * @param ExtName
     * @return
     */
    public static boolean isPicture(String ExtName) {

        String imgeArray[] = {"bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};
        for (int i = 0; i < imgeArray.length; i++) {
            if (imgeArray[i].equals(ExtName.toLowerCase(Locale.ENGLISH))) {
                return true;
            }

        }
        return false;
    }

    /**
     * 获取设备ID
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {

        String imei = "";
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                imei = telephonyManager.getImei();
                if (imei == null || imei.trim().length() == 0) {
                    imei = telephonyManager.getMeid();
                }
            } else {
                imei = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
            if (imei == null || imei.trim().length() == 0) {
                imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (imei == null || imei.trim().length() == 0) ? "" : imei.trim();

    }

    /**
     * 获取当前版本
     *
     * @param context
     * @return
     */
    public static int getLocalVersionCode(Context context) {
        int localVersion = 0;
        try {
            localVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * Base64转Object
     *
     * @param value
     * @return
     */
    public static String Base64Object(Object value) {
        String valueBase64 = "";
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(value);
            valueBase64 = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            oos.close();
        } catch (Exception e) {

        }
        return valueBase64;
    }

    /**
     * Base64转Object
     *
     * @param base64value
     * @return
     */
    public static Object DeBase64Object(String base64value) {
        Object obj = null;
        try {
            byte[] productBytes = Base64.decode(base64value.getBytes(), Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(productBytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            obj = ois.readObject();
            ois.close();

        } catch (Exception e) {

        }
        return obj;
    }

    /**
     * 判断是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info = conManager.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    public static NetworkInfo getNetworkInfo(Context context) {
        ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info = conManager.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return info[i];
                }
            }
        }
        return null;
    }

    //判断WiFi是否打开
    public static boolean isWiFiOpen(Context context) {
        WifiManager mWm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return mWm.isWifiEnabled();
    }

    /**
     * 计算bitmap的SampleSize
     *
     * @param options
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int targetWidth, int targetHeight) {

        final int outWidth = options.outHeight;
        final int outHeight = options.outWidth;
        int inSampleSize = 1;
        if (targetWidth <= 0 && targetHeight <= 0) {
            return 1;
        }
        if (targetWidth >= outWidth && targetHeight >= outHeight) {
            return 1;
        }

        do {
            inSampleSize *= 2;
        }
        while ((outWidth / inSampleSize) > targetWidth && (outHeight / inSampleSize) > targetHeight);

        // 然后根据比较像素总数的原则过滤掉那些比较极端的一边特别小，一边特别大的图片
        // 比如目标尺寸是400x400，图片的尺寸是6000*600，缩放后是3000*300
        // 这样看来的确是满足了第一个条件了，但是图片的尺寸依然很大
        // 因此这一步我们根据像素总数来过滤，规则是总像素数不得大于目标尺寸像素数的两倍
        long totalPixels = (outWidth / inSampleSize) * (outHeight / inSampleSize);
        final long totalReqPixelsCap = targetWidth * targetHeight * 2;
        while (totalPixels > totalReqPixelsCap) {
            inSampleSize *= 2;
            totalPixels /= 2;
        }

        return inSampleSize;
    }

    /**
     * 判断是否为中文字符
     *
     * @param chineseStr
     * @return
     */
    public static boolean isChineseCharacter(String chineseStr) {
        char[] charArray = chineseStr.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            if ((charArray[i] >= '\u0000' && charArray[i] < '\uFFFD') || ((charArray[i] > '\uFFFD' && charArray[i] < '\uFFFF'))) {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }
//	public static String getSingInfo(Context _context) {
//
//		String signNumber = "";
//		try {
//			PackageInfo packageInfo = _context.getPackageManager().getPackageInfo("com.meichis.yslpublicapp", PackageManager.GET_SIGNATURES);
//			Signature[] signs = packageInfo.signatures;
//			Signature sign = signs[0];
//			try {
//				CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
//				X509Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(sign.toByteArray()));
//				signNumber = cert.getSerialNumber().toString();
//
//			} catch (CertificateException e) {
//				e.printStackTrace();
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return signNumber;
//	}

    /**
     * 判断是否乱码
     *
     * @param str
     * @return
     */
    public static boolean isSpecialCharacter(String str) {
        if (str.contains("茂驴陆")) {
            return true;
        }
        return false;
    }

    /**
     * Json转Hashtable
     *
     * @param jsonStr
     * @param keys
     * @return
     */
    public static Hashtable<String, Object> JsonStrToHs(String jsonStr, String[] keys) {
        Hashtable<String, Object> hs = new Hashtable<String, Object>();
        try {
            JSONObject json = new JSONObject(jsonStr);
            for (String key : keys) {
                hs.put(key, json.get(key));
            }
        } catch (Exception e) {

        }
        return hs;
    }


    public static ArrayMap<String, Object> JsonStrToArrMap(String jsonStr) {
        ArrayMap<String, Object> map = new ArrayMap<>();
        try {
            JSONObject json = new JSONObject(jsonStr);
            Iterator keyIter = json.keys();
            while (keyIter.hasNext()) {
                String key = keyIter.next().toString();
                map.put(key, json.get(key));
            }
        } catch (Exception e) {

        }
        return map;
    }

    /**
     * GPS是否打开
     *
     * @param context
     * @return
     */
    public static final boolean isGPSOPen(final Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return gps;

    }

    /**
     * 获取网络类型（WIFI、CMCC、Unicom、Telecom）
     *
     * @param context
     * @return
     */
    public static String getNetType(Context context) {
        try {

            ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = conMan.getActiveNetworkInfo();
            if (info.getType() != ConnectivityManager.TYPE_MOBILE) {
                return "WIFI";
            }
            String IspName = "";
            switch (Tools.getISP(context)) {
                case 46000:
                case 46002:
                    IspName = "CMCC ";
                    break;
                case 46001:
                    IspName = "Unicom ";
                    break;
                case 46003:
                    IspName = "Telecom ";
                    break;
            }
            return IspName + info.getSubtypeName();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取网络ISP
     *
     * @param context
     * @return
     */
    public static int getISP(Context context) {
        try {
            TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String operator = telManager.getSimOperator();
            return Integer.parseInt(operator);
        } catch (Exception e) {
            return 0;
        }

    }

    /**
     * 获取网络名称（WIFI、移动、联通、电信）
     *
     * @param context
     * @return
     */
    public static String getNetTypeName(Context context) {
        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conMan.getActiveNetworkInfo();
        if (info != null && info.getType() != ConnectivityManager.TYPE_MOBILE) {
            return "WIFI";
        }
        String IspName = "";
        switch (Tools.getISP(context)) {
            case 46000:
            case 46002:
                IspName = "移动";
                break;
            case 46001:
                IspName = "联通";
                break;
            case 46003:
                IspName = "电信";
                break;
        }
        return IspName;
    }

    /**
     * 获取网络频段（WIFI、2G、3G、4G）
     *
     * @param context
     * @return
     */
    public static String getNetMode(Context context) {
        String mode = "";
        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conMan.getActiveNetworkInfo();
        if (info != null && info.getType() != ConnectivityManager.TYPE_MOBILE) {
            return "WIFI";
        }
        if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) {

            switch (info.getSubtype()) {
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                case TelephonyManager.NETWORK_TYPE_CDMA:
                case TelephonyManager.NETWORK_TYPE_GPRS:
                case TelephonyManager.NETWORK_TYPE_EDGE:
                case TelephonyManager.NETWORK_TYPE_IDEN:
                    mode = "2G";
                    break;
                case TelephonyManager.NETWORK_TYPE_UMTS:
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                case TelephonyManager.NETWORK_TYPE_EVDO_B:
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                case TelephonyManager.NETWORK_TYPE_HSPA:
                case TelephonyManager.NETWORK_TYPE_HSPAP:
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                case TelephonyManager.NETWORK_TYPE_EHRPD:
                    mode = "3G";
                    break;
                case TelephonyManager.NETWORK_TYPE_LTE:
                    mode = "4G";
                    break;
            }

        }
        return info.getSubtypeName() + "(" + mode + ")";
    }

    /**
     * 获取本地IP地址
     *
     * @return
     */
    public static String getLocalIpAddress() {

        try {

            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {

        }

        return "";

    }

    /**
     * Bitmap转String
     *
     * @param path 文件路径
     * @return
     */
    public static String bitmaptoString(String path) {
        FileInputStream fis;
        String uploadBuffer = null;
        try {
            fis = new FileInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = fis.read(buffer)) >= 0) {
                baos.write(buffer, 0, count);
            }
            uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));
            fis.close();
            baos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return uploadBuffer;
    }

    /**
     * 获取真实路径
     *
     * @param context
     * @param uri     文件的uri
     * @return
     */
    public static String getRealPathFromURI(Context context, Uri uri) {
        String[] arrayOfString = {"_data"};
        Cursor localCursor = context.getContentResolver().query(uri, arrayOfString, null, null, null);
        boolean bool = localCursor.moveToFirst();
        String str = null;
        if (bool)
            str = localCursor.getString(localCursor.getColumnIndexOrThrow("_data"));
        localCursor.close();
        return str;
    }


    /**
     * 生成二维码
     *
     * @param text 文字信息
     * @param side 图片边长
     * @return
     */
    public static Bitmap createQRcode(String text, int side) {
        try {
            Bitmap localBitmap = EncodingHandler.createQRCode(text, side);
            return localBitmap;
        } catch (WriterException localWriterException) {
            localWriterException.printStackTrace();
        }
        return null;
    }

    public static void hideKeyboard(Activity activity) {
        ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }


    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString().toUpperCase(Locale.getDefault());
    }

    public static String getNFCTagInfo(Parcelable[] data) {
        StringBuilder message = new StringBuilder();
        if (data != null) {
            try {
                for (int i = 0; i < data.length; i++) {
                    NdefRecord[] recs = ((NdefMessage) data[i]).getRecords();

                    for (int j = 0; j < recs.length; j++) {

                        if (recs[j].getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(recs[j].getType(), NdefRecord.RTD_TEXT)) {

                            byte[] payload = recs[j].getPayload();

                            String textEncoding = "UTF-16";
                            if ((payload[0] & 0200) == 0)
                                textEncoding = "UTF-8";

                            int langCodeLen = payload[0] & 0077;

                            message.append(new String(payload, langCodeLen + 1, payload.length - langCodeLen - 1, textEncoding));

                        } else
                            message.append(new String(recs[j].getPayload(), "UTF-8"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return message.toString();
    }

    public static String getWeekStr(String sdate) {
        String str = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        Date date = null;
        try {
            date = format.parse(sdate);
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            str = "周" + ("日一二三四五六".substring(c.get(Calendar.DAY_OF_WEEK) - 1, c.get(Calendar.DAY_OF_WEEK)));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return str;
    }

    public static boolean checkPackage(String packageName, Context context) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            // System.out.println("没有安装");
            return false;
        } else {
            // System.out.println("已经安装");
            return true;
        }
    }

    public static boolean OpenThridAPP(Context context, String pkg, String cls) {
        boolean isInstall = false;
        isInstall = checkPackage(pkg, context);
        if (isInstall) {
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName(pkg, cls);
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            context.startActivity(intent);
        }
        return isInstall;
    }

    @SuppressWarnings("unchecked")
    public static Fragment CreateClass(String ClassName) {
        Fragment CalssInstance = null;
        try {

            Class<Fragment> fragment = (Class<Fragment>) Class.forName(ClassName);

            CalssInstance = fragment.newInstance();

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return CalssInstance;
    }

    public static String filetoString(String path) {
        FileInputStream fis;
        String uploadBuffer = null;
        try {
            fis = new FileInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = fis.read(buffer)) >= 0) {
                baos.write(buffer, 0, count);
            }
            uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT)); // 进行Base64编码
            fis.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return uploadBuffer;
    }

    public static void stringtoFile(String base64Code, String savePath) throws Exception {

        String path = savePath.substring(0, savePath.lastIndexOf("/"));
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        byte[] buffer = Base64.decode(base64Code, Base64.DEFAULT);
        FileOutputStream out = new FileOutputStream(savePath);
        out.write(buffer);
        out.close();
    }

    public static String getFormatString(double value) {
        DecimalFormat formatter = new DecimalFormat("0.###");
        return formatter.format(value);
    }

    public static String getFormatString(double value, int length) {
        DecimalFormat formatter = new DecimalFormat("0.###".substring(0, 2 + length));
        return formatter.format(value);
    }

    public static PackageInfo getPackageInfo(Context context) {
        return getPackageInfo(context, context.getPackageName());
    }

    public static PackageInfo getPackageInfo(Context context, String packageName) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo;
    }

    public static Boolean CheckPassWordStrong(String PassWord) {
        if (PassWord.length() < 6)
            return false;

        char[] chars = PassWord.toCharArray();
        int count = 1;
        for (int i = chars.length - 1; i > 0; i--) {// 输出结果

            if (i > 0) {
                int Difference = (int) chars[i] - (int) chars[i - 1];
                count *= Difference != 0 ? Difference : 1;
            }
        }
        return Math.abs(count) > 50;
    }

    /**
     * 计算inflate过来的view的高和宽，计算完之后可以调用child.getMeasuredHeight()getMeasuredWidth()获取view内部控件的宽和高
     *
     * @param child
     */
    public static void measureView(View child) {
        ViewGroup.LayoutParams lp = child.getLayoutParams();
        if (lp == null) {
            lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        //headerView的宽度信息
        int childMeasureWidth = ViewGroup.getChildMeasureSpec(0, 0, lp.width);
        int childMeasureHeight;
        if (lp.height > 0) {
            childMeasureHeight = View.MeasureSpec.makeMeasureSpec(lp.height, View.MeasureSpec.EXACTLY);
            //最后一个参数表示：适合、匹配
        } else {
            childMeasureHeight = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);//未指定
        }
        //System.out.println("childViewWidth"+childMeasureWidth);
        //System.out.println("childViewHeight"+childMeasureHeight);
        //将宽和高设置给child
        child.measure(childMeasureWidth, childMeasureHeight);
    }

    public static void installApk(Context context, Uri apk) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(apk, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static void installApk(Context context, String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        Uri apk = Uri.fromFile(file);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(apk, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 资源文件拷贝
     *
     * @param context
     * @param fileName
     * @param path
     * @return
     */
    public static boolean copyApkFromAssets(Context context, String fileName, String path) {
        boolean copyIsFinish = false;
        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return copyIsFinish;
    }


    public static int getStrLength(String s) {
        if (s == null)
            return 0;
        char[] c = s.toCharArray();
        int len = 0;
        for (int i = 0; i < c.length; i++) {
            len++;
            if (!isLetter(c[i])) {
                len++;
            }
        }
        return len;
    }

    private static boolean isLetter(char c) {
        int k = 0x80;
        return c / k == 0 ? true : false;
    }

    public static byte[] strToGBKbytes(String str) {
        byte[] b = null, data = null;
        try {
            b = str.getBytes("utf-8");
            data = new String(b, "utf-8").getBytes("gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 判断手机是否root，不弹出root请求框<br/>
     */
    public static boolean isRoot() {
        String binPath = "/system/bin/su";
        String xBinPath = "/system/xbin/su";
        if (new File(binPath).exists() && isExecutable(binPath))
            return true;
        if (new File(xBinPath).exists() && isExecutable(xBinPath))
            return true;
        return false;
    }

    private static boolean isExecutable(String filePath) {
        Process p = null;
        try {
            p = Runtime.getRuntime().exec("ls -l " + filePath);
            // 获取返回内容
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String str = in.readLine();
            if (str != null && str.length() >= 4) {
                char flag = str.charAt(3);
                if (flag == 's' || flag == 'x') {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (p != null) {
                p.destroy();
            }
        }
        return false;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    public static int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) {
                newValue = 1; // Roll over to 1, not 0.
            }
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }


    private static void appendDeviceID(StringBuilder deviceId, String imei) {
        if (!TextUtils.isEmpty(imei)) {
            deviceId.append(deviceId.length() > 0 ? "," : "");
            deviceId.append(imei);
        }
    }

    public static String filetoString1(String path) {
        FileInputStream fis;
        String uploadBuffer = null;
        try {
            fis = new FileInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = fis.read(buffer)) >= 0) {
                baos.write(buffer, 0, count);
            }
//            uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT)); // 进行Base64编码
            uploadBuffer = new String(baos.toByteArray()); // 进行Base64编码
            fis.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return uploadBuffer;
    }

    /**
     * 不base64
     * @param base64Code
     * @param savePath
     * @throws Exception
     */
    public static void stringtoFile1(String base64Code, String savePath) throws Exception {

        String path = savePath.substring(0, savePath.lastIndexOf("/"));
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(savePath);
        out.write(buffer);
        out.close();
    }

    /**
     * 正则判断字符串是否base64加密过
     * @param str
     * @return
     */
    public static boolean isBase64(String str) {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        return Pattern.matches(base64Pattern, str);
    }

    /**
     * 判断字符是否是中文
     *
     * @param c 字符
     * @return 是否是中文
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否乱码
     * @param strName
     * @return
     */
    public static boolean isMessyCode(String strName) {
        try {
            Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
            Matcher m = p.matcher(strName);
            String after = m.replaceAll("");
            String temp = after.replaceAll("\\p{P}", "");
            char[] ch = temp.trim().toCharArray();

            int length = (ch != null) ? ch.length : 0;
            for (int i = 0; i < length; i++) {
                char c = ch[i];
                if (!Character.isLetterOrDigit(c)) {
                    String str = "" + ch[i];
                    if (!str.matches("[\u4e00-\u9fa5]+")) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static String getJOStrItem(String key, JSONObject jo) {
        String value = "";
        try {
            if (jo.has(key)) {
                value = jo.getString(key);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return value;
    }

    //view 转bitmap

    public static Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        Bitmap bitmap = view.getDrawingCache();

        return bitmap;

    }

}
